

const _tinyUrlResultRegExStr = "<input\\s*type=hidden\\s*name=tinyurl\\s*value=\"(http:\\/\\/tinyurl\\.com\\/[^\"'\\s>]*)\"\\s*>";
const _tinyUrlExcludeRegExStr = "http:\\/\\/((.)*\\.)?tinyurl\\.com";
var _tinyThresholdAck = false;
var _smallThreshold=15;
//default: true--comment is eligible for tinyrul conversion
//if _tinyToggle is false, don't perform conversion
var _tinyToggle = true; 

var swakMaxPostLength = 250;



function registerChatPostListener(doc) {
	if (doc == null) doc=content.document;
	var postDiv = doc.getElementById('chatPost');  //post_a_comment

		var chatcomment = doc.getElementById('comment_comment');
		if (chatcomment != null) {
			chatcomment.addEventListener('keyup', function(event) {
				try {
			 		var count = event.target.value.length;
			 		if (count > swakMaxPostLength) {
			 			event.target.style.border='2px dotted #FF9900';
			 			event.target.title=count + ', Max Post Length Is 250 Characters';
			 			//alert('count ' + count);
			 		}
			 		else {
			 			event.target.style.border='none';
			 			event.target.title='';
			 		}
				}
				catch (x){}
			}, false);
		}
	
		postDiv.addEventListener('submit', function(event) {
			var comment = content.document.getElementById('comment_comment');
			//check to see if tiny conversion was overridden, reset back to true
			//reset border
			if (_tinyToggle == false) {
				_tinyToggle = true;
				comment.style.border='none';
				return;
			}

			var enabled = SS_getPreference(SMACK_TINYURL_ENABLE);
			if (enabled == false) return;
			var threshold = SS_getPreference(SMACK_TINYURL_THRESHOLD);
			
			if (comment == null || comment.value == null || comment.value == "") return;
			
			
			var urlsInChat = SS_getChatPostUrlText(comment.value);
			//alert(urlsInChat);
			if (urlsInChat == null || urlsInChat.length==0) return;
			if (_tinyThresholdAck == false && threshold <_smallThreshold) {
				var info = SS_getStringTableText('tinyurl_info1');
				alert(info);
				_tinyThresholdAck = true;
			}
			for (var i=0;i<urlsInChat.length;i++) {
				var urlInChat = urlsInChat[i];
				
				if (urlInChat == null || urlInChat.length < threshold) continue;
				//check to see if url is already a tinyurl...if so, skip it
				var excludeTiny = new RegExp(_tinyUrlExcludeRegExStr,"i");
				var tinyFound = excludeTiny.test(urlInChat);
				if (tinyFound == true) {
					continue;
				}
			
			//create new request to tinyurl
			var tu = new TinyUrlRequest(urlInChat);
 			var tinyChatCB = {
			ondone : function(handle){

					urlInChat = SS_escapeRegExLiterals(urlInChat);
					//alert('literal replaced urlregex ' + urlInChat);
					var ureg = new RegExp(urlInChat,"i");
					comment.value = comment.value.replace(ureg,handle.tinyUrlResult);
					//alert(handle.tinyUrlResult);
					//alert('converted value ' + comment.value);
			},
			
			onerror : function(handle){
				var error = SS_getStringTableText('humor_error1');
				alert(error);
			}
		}

 	tu.execute(tinyChatCB);
		} //end for
	}, true);
	
//http://developer.mozilla.org/en/docs/XUL:browser#p-docShell
	//added dblclick listener to allow individual tinyurl post toggle
	//e.g. turn tinyurl off (or back on) for a single post 
	var cc = doc.getElementById('comment_comment');
	cc.addEventListener('dblclick',function(event) {
		//just for quick test
	//	alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) current state: ' + swaksmack.alertManager.state);
//	var ggcalcw=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','chrome,height=400,width=500');
		//if (swaksmack.alertManager.alertPresent(SMACK_ALERT_OUTWITOPTIN)) alert('alert already present');
		//_TEST
		
		//TEST http
		/*
					var jfpm = new JellyFishInfoRequest('');
 			var jfInfoCB = {
			ondone : function(handle){
					alert(handle.infoChatResult+ ' JF PM check done ' + handle.infoPMResult);
					//urlInChat = SS_escapeRegExLiterals(urlInChat);
					//alert('literal replaced urlregex ' + urlInChat);
					//var ureg = new RegExp(urlInChat,"i");
					//comment.value = comment.value.replace(ureg,handle.infoResult);
					//alert(handle.tinyUrlResult);
					//alert('converted value ' + comment.value);
			},
			
			onerror : function(handle){
				//var error = SS_getStringTableText('humor_error1');
				alert('JFInfoCB--onerror--may not be an error at this time');
			}
		}

 	jfpm.execute(jfInfoCB);
 	
 	
 	
 	
 	
 	*/
 	//alert(' state swaksmack.SS_JF.getState() ' + swaksmack.SS_JF.getState());
 	/*
 	alert(SS_oldState + ' old state, state swaksmack.SS_JF.getState() ' + swaksmack.SS_JF.getState());
 	var product = swaksmack.SmackShopDoc.getElementById('productNameAnchor');
 	var pt = product.textContent;
 	//alert('pre create APR');
 				var tu = new AmazonProductRequest(pt);  //was pt
 			var amazonCB = {
			ondone : function(handle){
					alert('APR done');
					var list = handle.amazonInfoList;
					if (list == null) return;
					var api = list.shift();
					alert('url: ' + api.prodURL + ' price: ' + api.prodPrice);
					//urlInChat = SS_escapeRegExLiterals(urlInChat);
					//alert('literal replaced urlregex ' + urlInChat);
					//var ureg = new RegExp(urlInChat,"i");
					//comment.value = comment.value.replace(ureg,handle.tinyUrlResult);
					//alert(handle.tinyUrlResult);
					//alert('converted value ' + comment.value);
			},
			
			onerror : function(handle){
				
				alert('APR error');
			}
		}
 	tu.execute(amazonCB);
 	*/
 	
 	//alert(dst);
 	/*
swakReplaceAllCaps('ALL CAPS');
swakReplaceAllCaps('no caps');
swakReplaceAllCaps('First Caps');
swakReplaceAllCaps('ROTFLMAO');
swakReplaceAllCaps('ROTFLMAO OMG WTF BFD');
swakReplaceAllCaps('AB CD EF GHIJ');
*/
//alert(swakReplaceAllCaps('***********AB DF ++JK &&&&LO=== CD%%%% $$$$EF  :::::::::::GH ####ME ^^^^^TO^^^^^^ BE @@@@HI FI WI***********************************'));

//alert(swakReplaceAllCaps('*********** AB  $$$$EF  HE FR TY IO ******************'));
 	
 	

 	
// 	if (Date.parse(today) > Date.parse(dst[0])) {
// 	}
 //	var cw = SS_getSmackShoppingWindow();
//	alert( swaksmack.SmackShopDoc + ', shopdoc, tucw ' + cw);
 //	alert('typeid: '+ swaksmack.SS_JF.getTypeIdentifier() +', ' +swaksmack.SS_JF.getState() + ' smack poll alert ack: ' + swakalerts.smakpotAlertAck + ', outwit optin ack: '+ swakalerts.outwitAlertAck);
	//	alert(swaksmack.SS_JF.getSmackMostRecentCommentId() + ' recent comment,  state ' + swaksmack.SS_JF.getState());
	//	alert(swaksmack.SS_JF.getFirstChatId(swaksmack.smackShopContentWindow) + ' first, CM last ' + swaksmack.SS_JF.getLastChatId(swaksmack.smackShopContentWindow));
		//_TEST
		var commentdiv = event.target;
		_tinyToggle = !_tinyToggle;
		if (_tinyToggle == false) {
			commentdiv.style.border='2px solid #BF250E';
		}
		else {
			commentdiv.style.border='none';
		}
	}, true);
	
}


function TinyUrlRequest(url1){

	this.sourceURL = url1;
	
	//result url from tinurl
	this.tinyUrlResult = null;
	
	//tinyurl httprequest
	this.request = null;
	
	
	//execute the tiny url request
	this.execute = function(callback){
		
		// No need to shrink
		if(this.tinyUrlResult != null){
			return;
		}
		
		// check if there is an outstanding request
		if(this.request != null){
			this.request.abort();
		}
		
		// Setup Request	
		this.request	= new XMLHttpRequest();
		this.request.open("POST", "http://tinyurl.com/create.php", false); //(default)true:async - false: sync
		this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.request.setRequestHeader("User-Agent", navigator.userAgent);
		this.request.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

		
		//url substitutions
		var url = this.sourceURL;
   	url = url.replace(/\+/g, "%2B").replace(/&/g, '%26').replace(/\?/g, '%3F').replace(/=/g, '%3D');       	
		
		//store reference to stuff
		var handle = this;

		
		// Handle request
		this.request.onload = {
			handleEvent : function(e){
				
				// If already aborted
				if(handle.request == null){
					return;
				}
				
				//get html from response and look for tunyurl
				var html = handle.request.responseText;
				handle.tinyUrlResult = null;
				
				var regexp	= new RegExp(_tinyUrlResultRegExStr, "i");
				var tinyresult	= regexp.exec(html);
				//alert('tinyresult ' + tinyresult);
				if(tinyresult != null && tinyresult.length > 0){
					handle.tinyUrlResult = tinyresult[1];  				
				}
				

				
				// callback to onerror or ondone
				if(handle.tinyUrlResult == null || handle.tinyUrlResult==""){
					callback.onerror(handle);
				}
				else{
					//should just be sending back the tunyurl as a string
					callback.ondone(handle);
				}
			}
		};
		
		// check if the xmlhttprequest had an error--if so, callback to error
		this.request.onerror = {
			handleEvent : function(e){
				callback.onerror(handle);
			}
		}
       	      	
    //send request
    this.request.send("url="+ url);
	}
	

//cancel the request
	this.cancel = function(){
		try{
			this.request.abort();
		}catch(e){  }
	}
}
